//
//  UIViewController_Ex.swift
//  DawnFoundation
//
//  Created by 崔成成 on 2021/8/22.
//

import UIKit

extension UIViewController {

    public func push(_ vc: UIViewController, animated: Bool = true) {
        vc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(vc, animated: animated)
    }
    
    public func push(type: UIViewController.Type, animated: Bool = true) {
        push(type.init(), animated: animated)
    }
    
    func pushAndReplace(type: UIViewController.Type, animated: Bool = true) {
        let vc = type.init()
        var vcs = navigationController?.viewControllers
        vcs?.removeLast()
        navigationController?.setViewControllers(vcs ?? [], animated: false)
        push(vc, animated: animated)
    }
    
    func pushAndUtil(type: UIViewController.Type, animated: Bool = true) {
        let vc = type.init()
        navigationController?.setViewControllers([], animated: false)
        push(vc, animated: animated)
    }
    
    @objc func back(animated: Bool = true) {
        guard let vcs = navigationController?.viewControllers, vcs.count > 1 else {
            navigationController?.dismiss(animated: animated)
            return
        }
        navigationController?.popViewController(animated: animated)
    }
    
    func back(to type: UIViewController.Type, animated: Bool = true) {
        guard let vcs = navigationController?.viewControllers, vcs.count > 1 else {
            navigationController?.dismiss(animated: animated)
            return
        }
        var _vc: UIViewController?
        for i in 0..<vcs.count {
            let vc = vcs[i]
            if vc.isKind(of: type.classForCoder()) {
                _vc = vc
                break
            }
        }
        if _vc != nil {
            navigationController?.popToViewController(_vc!, animated: animated)
        }
    }
    
    func backUtil(animated: Bool = true) {
        guard let vcs = navigationController?.viewControllers, vcs.count > 1 else {
            navigationController?.dismiss(animated: animated)
            return
        }
        navigationController?.popToRootViewController(animated: animated)
    }

}
